package com.ct.lotterysystem2.service.impl;

import com.ct.lotterysystem2.common.errorcode.ServiceErrorCodeConstants;
import com.ct.lotterysystem2.common.exception.ServiceException;
import com.ct.lotterysystem2.common.utils.CaptchaUtil;
import com.ct.lotterysystem2.common.utils.MailUtil;
import com.ct.lotterysystem2.common.utils.RedisUtil;
import com.ct.lotterysystem2.common.utils.RegexUtil;
import com.ct.lotterysystem2.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String VERIFICATION_CODE_PREDIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;

    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void sendVerificationCode(String email) {
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }

        // 生成验证码
        String code = CaptchaUtil.getCaptcha(4);

        // 发送验证码
        // 发送到邮箱里
        mailUtil.sendSampleMail(email, "验证码", code);

        // 将验证码存进缓存
        redisUtil.set(VERIFICATION_CODE_PREDIX + email, code, VERIFICATION_CODE_TIMEOUT);

    }

    @Override
    public String getVerificationCode(String email) {
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREDIX + email);
    }
}
